//
//  WBWelcomeView.swift
//  SinaMicroblog
//
//  Created by 原鹏飞 on 2017/4/8.
//  Copyright © 2017年 YuanPengFei. All rights reserved.
//

import UIKit
import SDWebImage   //导入框架

class WBWelcomeView: UIView {
    //头像
    lazy var iconView: UIImageView = {
        let imageView = UIImageView()
        imageView.sd_setImage(with: URL(string: WBUserAccount.shared.avatar_large!)!, placeholderImage: UIImage(named: "avatar_default_big")!)
        
        return imageView
    }()
    
    //欢迎蚊子的label
    lazy var welcomeLabel: UILabel = UILabel(title: "欢迎归来, \(WBUserAccount.shared.screen_name!)", fontSize: 15, alignment: .center)
    
    override func layoutSubviews() {
        super.layoutSubviews()
        print(#function)
    }
    
    //已经加载到屏幕
    override func didMoveToWindow() {
        super.didMoveToWindow()
        //添加动画, 要在当前视图已经显示到屏幕之后添加
        addAnimation()
    }
    
    override init(frame: CGRect) {
        super.init(frame: screenBounds)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


extension WBWelcomeView {
    
    /// 设置UI
    func setupUI() {
        print(#function)
        
        self.backgroundColor = UIColor.white
        
        //1. 设置头像圆角
        iconView.layer.cornerRadius = 45
        iconView.layer.masksToBounds = true
        
        //2. 添加子视图
        addSubview(iconView)
        addSubview(welcomeLabel)
        
        //3. 自动布局
        iconView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-120)
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-150)
        }
        
        //4. 在动画执行之前, 需要先强制更新UI的布局(强制调用layoutifNeeded), 该方法调用之后, 上面的自动布局的设置才会生肖
        layoutIfNeeded()
    }
    
    
    /// 添加动画
    func addAnimation() {
        iconView.snp.updateConstraints { (make) in
            make.centerY.equalTo(self).offset(-150)
        }
        
        //usingSpringWithDamping: 弹力系数, 越小越弹
        //initialSpringVelocity: 重力系数
        UIView.animate(withDuration: 3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 9.8, options: [], animations: {
            self.layoutIfNeeded()
        }) { (isFinish) in
            self.removeFromSuperview()
        }
    } 
}
